package grailsforum

import org.springframework.validation.ObjectError

class PostsController {

    static allowedMethods = [

            addPost: 'POST',
            editPost: 'POST'
    ]

    def addPost(){

        Thread thread = Thread.get(params.thread)

        Post post = new Post(
                thread  : thread,
                text    : params.text,
                position: thread.posts.size(),
                date    : new Date(),
                user    : User.get(params.user)
        )

        if (!post.save()){

            render message(error: post.errors.allErrors.first())
            return;
        }

        render "ok"
    }

    def editPost(){

        Post post = Post.get(params.post)
        post.text = params.text

        if (!post.save()){

            render message(error: post.errors.allErrors.first())
            return;
        }

        render "ok"
    }

    def deletePost(){

        Post post = Post.get(params.post)
        Thread thread = Thread.get(params.thread)

        thread.posts.each {

            if(it.position > post.position){

                it.position--
            }
        }

        thread.posts.remove(post);

        /*
        post.votes.each {

            it.delete()
        }
        */

        post.delete()
        thread.save()

        render "ok"
    }
}
